package com.qingmeng.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.qingmeng.apiclientsdk.config.ApiMethodConfig;
import com.qingmeng.apiclientsdk.dto.RequestParams;
import com.qingmeng.apiclientsdk.entry.ApiResponse;
import com.qingmeng.apiclientsdk.entry.Response;
import com.qingmeng.apiclientsdk.entry.User;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import static com.qingmeng.apiclientsdk.utils.SignUtils.getSign;

/**
 * 接口调用客户端
 * @author  清梦
 */
public class ApiClient {

    private static final String GATEWAY_HOST = "http://localhost:8090/api";

    // accessKey
    private String accessKey;

    // secretKey
    private String secretKey;

    @Resource
    private ApiMethodConfig apiMethodConfig;

    // 根据 URL 路径调用相应的方法并返回 ApiResponse
    public ApiResponse<?> invokeMethod(ApiMethodConfig apiMethodConfig, RequestParams<?> params) {
        Map<String, String> methodMap = apiMethodConfig.getMethodMap();
        String interfacePath = params.getUrl();
        String methodName = methodMap.get(interfacePath);

        if (methodName == null) {
            return ApiResponse.failure("Unknown URL path: " + interfacePath);
        }

        try {
            // 获取方法对象
            // todo 感觉这里等待参数类型不能写死，每个接口都需要在这里判断
            // 暂时线固定使用Json的参数类型User.class
            Method method = this.getClass().getDeclaredMethod(methodName, User.class);

            // 设置私有方法可访问（如果需要）
//            method.setAccessible(true);

            Object body = params.getBody();
            System.out.println("用户的请求参数：" + body);
            Object result = null;
           try  {
               // 调用方法并传递参数
               result = method.invoke(this, body);
           }catch (Exception e){
               return ApiResponse.failure("方法调用失败: " + methodName);
           }
            return ApiResponse.success(result);
        } catch (NoSuchMethodException e) {
            return ApiResponse.failure("Method not found: " + methodName);
        }catch (IllegalArgumentException e) {
            return ApiResponse.failure("Invalid arguments for method: " + methodName);
        }
    }


    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    // 调用接口---------------------------------------------------------
    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String string = null;
        try {
           string = HttpUtil.get(GATEWAY_HOST + "/name/get", paramMap);
        }catch (Exception e){
           throw new RuntimeException("接口调用异常" + e);
        }
        return string;
    }
    public String getNameByPost(String name) {

        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        // 调用接口
        String string = null;
        try {
            string = HttpUtil.post(GATEWAY_HOST + "/name/post", paramMap);
        }catch (Exception e){
            throw new RuntimeException("接口调用异常" + e);
        }
        //响应结果
        return string;
    }
    public String getNameByJson(User user){

        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = null;
        try {
            httpResponse = HttpRequest.post(GATEWAY_HOST + "/name/json")
                  .addHeaders(getHeadersMap(json))
                  .body(json)
                  .execute();
        } catch (Exception e) {
            throw new RuntimeException("接口调用异常" + e);
        }
//        int status = httpResponse.getStatus();
//        String body = httpResponse.body();
//        System.out.println("请求状态为：" + status);
//        System.out.println("请求体为：" + body);
//        Response response = new Response();
//        response.setStatus(httpResponse.getStatus());
//        response.setMessage(httpResponse.body());
        if (!httpResponse.isOk()){
            throw new RuntimeException("请求失败");
        }
        return httpResponse.body();
    }

    /**
     *  获取请求头
     * @param body
     * @return
     * @throws UnsupportedEncodingException
     */
    private Map<String , String> getHeadersMap(String body) throws UnsupportedEncodingException {
        Map<String, String> headerMap = new HashMap<>();
        // 设置AK
        headerMap.put("accessKey", accessKey);
        // 设置SK （不能直接发送密钥）
//        headerMap.put("secretKey", secretKey);
        // 设置请求体
        // 为防止中文乱码，这里对body重新编码
        String newBody = URLEncoder.encode(body, "utf-8");
        headerMap.put("body", newBody);
        // 设置nonce 随机数
        headerMap.put("nonce", RandomUtil.randomNumbers(4));
        // 设置时间戳
        headerMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        // 设置签名sign
        headerMap.put("sign", getSign(newBody, secretKey));
        return headerMap;
    }

}
